package org.tinygroup.xmlsignaturefilter;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.tinygroup.commons.tools.StringEscapeUtil;
import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.weblayer.AbstractTinyFilter;
import org.tinygroup.weblayer.WebContext;
import org.tinygroup.xmlparser.XmlDocument;
import org.tinygroup.xmlparser.parser.XmlStringParser;
import org.tinygroup.xmlsignature.impl.StringXmlSignatureHelper;

/**
 * 验证XML数字签名的过滤器
 * @author yancheng11334
 *
 */
public class XmlSignatureTinyFilter extends AbstractTinyFilter{

	private String headerName ;
    private StringXmlSignatureHelper helper = new StringXmlSignatureHelper();
	
	public void preProcess(WebContext context) throws ServletException,
			IOException {
	}

	public void postProcess(WebContext context) throws ServletException,
			IOException {
	}
	
	public WebContext getAlreadyWrappedContext(WebContext wrappedContext) {
		HttpServletRequest request = wrappedContext.getRequest();
		try {
			boolean tag = checkRequestHeader(request);
			return new XmlSignatureWebContextImpl(wrappedContext,tag);
		} catch (Exception e) {
			throw new RuntimeException("验证XML数字签名发生异常",e);
		}
	}
	
	private boolean checkRequestHeader(HttpServletRequest request) throws Exception{
		String xml = request.getHeader(headerName);
		if(xml!=null){
		   xml = StringEscapeUtil.unescapeURL(xml, "UTF-8");
		   XmlDocument doc = new XmlStringParser().parse(xml);
		   String userId = doc.getRoot().getSubNode("UserId").getContent();
		   ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		   //需要取反
		   return !helper.getXmlSignatureProcessor().validateXmlSignature(userId, input);
		}
		return false;
	}

	protected void customInit() {
		headerName = StringUtil.defaultIfEmpty(get("headerName"), "tiny-xmlsignature");
	}

}
